#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import click
from DrissionPage import Chromium, ChromiumOptions
from colorama import init, Fore
from DrissionPage._functions.elements import ChromiumElementsList
from Utils.SuperInput import SuperInput
from Utils.Tool import ConsoleInfo
from threading import Thread
import sys


@click.command()
@click.option("--debugport", "-p", default=9222, help="debug port")
@click.option("--url", "-url", default="https://www.baidu.com/", help="url")
def start(debugport, url):
    init()
    SI = SuperInput()

    console = ConsoleInfo()
    console.help("full")

    # 创建配置对象
    co = ChromiumOptions()
    co.set_local_port(debugport)  # 设置本地端口号

    # 创建浏览器对象
    browser = Chromium(co)
    tab = browser.latest_tab
    tab.get(url)

    # 打印页面标题
    print(tab.title)

    def port():
        return browser._chromium_options.address.split(":")[1]

    def tishi():
        return f"browser({port()})/tab({browser.latest_tab.url}) >"

    def toRed(text):
        text = str(text)
        return Fore.RED + text + Fore.RESET

    def toGreen(text):
        text = str(text)
        return Fore.GREEN + text + Fore.RESET

    def toBlue(text):
        text = str(text)
        return Fore.BLUE + text + Fore.RESET

    def toYellow(text):
        text = str(text)
        return Fore.YELLOW + text + Fore.RESET

    def inject_js(tab):
        script_path = os.path.abspath(__file__)
        script_dir = os.path.dirname(script_path)
        js_path = os.path.join(
            script_dir, "Utils", "onMouseElement.js"
        )  # 组合出js文件的路径
        # print(js_path)
        tab.run_js(js_path)
        # tab.run_js(code)
        Thread(target=listen_console, args=(tab,)).start()

    def listen_console(tab):
        if tab.console.listening:
            return
        tab.console.start()
        while True:
            data = tab.console.wait().text
            if "语法捕获:" in data:
                datalist = data.split("语法捕获:")
                dd = datalist[0] + Fore.LIGHTGREEN_EX + datalist[1] + Fore.RESET
                print(dd)

    class Path:
        b = f"browser({port()})"
        tab = f"tab({browser.latest_tab.url})"
        mode = "python"

        def get_tab():
            return f"tab({browser.latest_tab.url})"

        def get_title():
            return browser.latest_tab.title

        def get():
            return f"{Path.b}_{Path.get_title()}\n[{Path.mode}]"

    # └─
    class History:
        def __init__(self):
            self.history = []

        def add(self, text):
            self.history.append(text)

        def get_last(self):
            return self.history[-1] if self.history else None

        def get_all(self):
            return self.history

        def clear(self):
            self.history = []

        def print_all(self):
            for index, i in enumerate(self.history):
                print(Fore.GREEN + f"[{index}] {i}" + Fore.RESET)

        def print_last(self):
            print(
                Fore.GREEN
                + f"[{len(self.history) - 1}] {self.history[-1]}"
                + Fore.RESET
            )

    history = History()

    EXIT_CMD = {"exit", "quit", "q"}

    def exe(expression: str):
        tab = browser.latest_tab
        if expression == "":
            return
        if expression == "help":
            console.help("simple")
            return
        expression = tranlate_str(expression)
        try:
            result = eval(expression)
            if type(result) == ChromiumElementsList:
                for index, i in enumerate(result):
                    print(Fore.GREEN + f"[{index}] {i}" + Fore.RESET)
                return

            print(Fore.GREEN + str(result) + Fore.RESET)
        except Exception as e:
            print(Fore.RED + f"发生错误: {e}" + Fore.RESET)

    def tranlate_str(s):
        def _is_chinese_start(s):
            return len(s) > 0 and "\u4e00" <= s[0] <= "\u9fa5"

        if s.startswith("//"):
            b = f"tab.eles('x:{s}')"
        elif s.startswith("t:") or s.startswith("tag:") or _is_chinese_start(s):
            b = f"tab.eles('{s}')"
        elif s.startswith("www."):
            b= f"tab.get('https://{s}')"    
        else:
            b = s
        print("自动转换并执行: " + Fore.LIGHTRED_EX + b + Fore.RESET)
        return b

    def main():
        """主循环"""
        browser.latest_tab.run_js(" console.clear();")

        while True:
            inject_js(browser.latest_tab)
            print("\n" + "-" * 10 + "DP Shell 1.0 - " + "\n")
            print(Fore.LIGHTBLUE_EX + Path.get() + Fore.RESET)
            user_input = SI.input("->")
            # print(Fore.YELLOW+user_input+Fore.RESET)
            if user_input.lower() in EXIT_CMD:
                sys.exit()
                break

            exe(user_input)

    main()


if __name__ == "__main__":
    start()
